package com.by.heartbeats.filter;

import com.by.toolkit.consts.ByContextConst;
import com.by.toolkit.consts.WebGlobalConst;
import com.by.toolkit.platform.ByContext;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 企业代码过滤器
 *
 * @author YanBingHao
 * @since 2025/10/10
 */
@Slf4j
@Order(Integer.MIN_VALUE + 4)
@Component
public class CorpCodeFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        String corpCode = request.getHeader(WebGlobalConst.CORP_CODE);
        log.info("[CorpCodeFilter][doFilter] uri:[{}] corpCode:[{}]", requestURI, corpCode);
        if (StringUtils.isBlank(corpCode)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        ByContext.put(ByContextConst.CORP_CODE, corpCode);
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            ByContext.remove();
        }
    }

}
